package Meituan;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 伯努利定理
 * @author: leiwenkang02@meituan.com
 * @date: 2019/3/4
 * @time: 15:52
 */
public class BonuliTest2 {

    // String 可以为任意类型 也可以自定义类型
    static Map<Double, Double> keyChanceMap = new HashMap<Double, Double>();
    static {
        keyChanceMap.put(2.5, 0.2);
        keyChanceMap.put(3.0, 0.6);
        keyChanceMap.put(3.5, 0.1);
        keyChanceMap.put(4.0, 0.1);
    }

    public static void main(String[] args) {
        Map<Double, Integer> countMap = new HashMap<Double, Integer>();
        Double item = null;
        int count = 10000;
        for (int i = 0; i < count; i++) {
            item = chanceSelect(keyChanceMap);
            if (countMap.containsKey(item)) {
                countMap.put(item, countMap.get(item) + 1);
            } else {
                countMap.put(item, 1);
            }

        }
        for (Double id : countMap.keySet()) {
            System.out.println(id + "\t出现的概率为 " + BigDecimal.valueOf(countMap.get(id)).divide(BigDecimal.valueOf(count), 3, 4).setScale(2, 4).doubleValue());
        }
    }

    public static Double chanceSelect(Map<Double, Double> keyChanceMap) {

        double rand = Math.random();

        for (Map.Entry<Double, Double> entry : keyChanceMap.entrySet()) {
            rand -= entry.getValue();
            // 选中
            if (rand <= 0) {
                return entry.getKey();
            }
        }
        return null;
    }
}
